from datetime import datetime, date
from app.models.mysql_db import db

class AirDataStats(db.Model):
    """空气数据统计模型 - 存储最近100条数据的平均值"""
    __tablename__ = 'air_data_stats'
    
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.Integer, db.ForeignKey('devices.id'), nullable=False)
    date = db.Column(db.Date, default=date.today)  # 添加日期字段
    avg_temperature = db.Column(db.Float)
    avg_humidity = db.Column(db.Float)
    avg_pm25 = db.Column(db.Float)
    avg_pm10 = db.Column(db.Float)
    avg_co2 = db.Column(db.Float)
    avg_tvoc = db.Column(db.Float)
    sample_count = db.Column(db.Integer, default=0)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 建立关系
    device = db.relationship('Device', backref=db.backref('air_stats', uselist=False))
    
    def __init__(self, device_id):
        self.device_id = device_id
        self.sample_count = 0
    
    def update_stats(self, new_data):
        """更新统计数据"""
        # 设置当前日期
        self.date = date.today()
        
        if self.sample_count >= 100:
            # 如果已有100条数据，则使用滑动窗口更新
            weight_old = 99/100
            weight_new = 1/100
            
            self.avg_temperature = self.avg_temperature * weight_old + new_data.get('temperature', 0) * weight_new
            self.avg_humidity = self.avg_humidity * weight_old + new_data.get('humidity', 0) * weight_new
            self.avg_pm25 = self.avg_pm25 * weight_old + new_data.get('pm25', 0) * weight_new
            self.avg_pm10 = self.avg_pm10 * weight_old + new_data.get('pm10', 0) * weight_new
            self.avg_co2 = self.avg_co2 * weight_old + new_data.get('co2', 0) * weight_new
            self.avg_tvoc = self.avg_tvoc * weight_old + new_data.get('tvoc', 0) * weight_new
        else:
            # 如果不足100条数据，则使用累积平均
            n = self.sample_count
            
            if n == 0:
                self.avg_temperature = new_data.get('temperature', 0)
                self.avg_humidity = new_data.get('humidity', 0)
                self.avg_pm25 = new_data.get('pm25', 0)
                self.avg_pm10 = new_data.get('pm10', 0)
                self.avg_co2 = new_data.get('co2', 0)
                self.avg_tvoc = new_data.get('tvoc', 0)
            else:
                self.avg_temperature = (self.avg_temperature * n + new_data.get('temperature', 0)) / (n + 1)
                self.avg_humidity = (self.avg_humidity * n + new_data.get('humidity', 0)) / (n + 1)
                self.avg_pm25 = (self.avg_pm25 * n + new_data.get('pm25', 0)) / (n + 1)
                self.avg_pm10 = (self.avg_pm10 * n + new_data.get('pm10', 0)) / (n + 1)
                self.avg_co2 = (self.avg_co2 * n + new_data.get('co2', 0)) / (n + 1)
                self.avg_tvoc = (self.avg_tvoc * n + new_data.get('tvoc', 0)) / (n + 1)
            
            self.sample_count = min(n + 1, 100)
        
        self.updated_at = datetime.utcnow()
    
    def to_dict(self):
        """转换为字典"""
        return {
            'device_id': self.device_id,
            'date': self.date.isoformat() if self.date else None,
            'avg_temperature': round(self.avg_temperature, 2) if self.avg_temperature is not None else None,
            'avg_humidity': round(self.avg_humidity, 2) if self.avg_humidity is not None else None,
            'avg_pm25': round(self.avg_pm25, 2) if self.avg_pm25 is not None else None,
            'avg_pm10': round(self.avg_pm10, 2) if self.avg_pm10 is not None else None,
            'avg_co2': round(self.avg_co2, 2) if self.avg_co2 is not None else None,
            'avg_tvoc': round(self.avg_tvoc, 2) if self.avg_tvoc is not None else None,
            'sample_count': self.sample_count,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }